import React from 'react';
import styles from './index.less';
import { DatePicker } from 'antd';
// components
import { TRMessage } from '@/components';
import { CalendarOutlined } from '@/utils/antdIcons';

export default (props) => {
  const { value = null, onChange = () => {} } = props;
  const dateFmt = 'MMDD';
  const [dates, setDates] = React.useState(null);
  const [open, setOpen] = React.useState(false);

  const _onChangeDates = (dates) => {
    setDates(null);
    setOpen(false);
    if (dates[0].year() !== dates[1].year()) {
      return TRMessage.error('执行周期不能跨年!');
    }
    onChange?.(dates);
  };

  return (
    <div className={styles.date_range}>
      <div
        className={styles.date_range__shower}
        onClick={() => {
          setDates([null, null]);
          setOpen(!open);
        }}
      >
        {value?.length ? (
          <div>{`${value[0].format(dateFmt)} - ${value[1].format(dateFmt)}`}</div>
        ) : (
          <div className={styles.date_range__placeholder}>请选择日期</div>
        )}
        <CalendarOutlined />
      </div>
      <div className={styles.date_range__picker}>
        <DatePicker.RangePicker
          open={open}
          value={dates || value}
          onChange={_onChangeDates}
          allowClear={false}
          bordered={false}
          format={dateFmt}
          separator="-"
          onCalendarChange={(vals) => {
            // 首选开始时间
            const _dates = !vals[0] ? vals.reverse() : vals;
            setDates(_dates);
          }}
        />
      </div>
      {open && (
        <div
          className={styles.date_range__mask}
          onClick={() => {
            setDates(null);
            setOpen(false);
          }}
        />
      )}
    </div>
  );
};
